﻿using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using System.Web.Mvc;
using Capacitacion.Models;
using Capacitacion.Queries;

namespace Capacitacion.Controllers
{
    public class ReviewsController : Controller
    {

        //
        // GET: /Reviews/

        readonly RestaurantsContext _context = new RestaurantsContext();

        public PartialViewResult LatestReviews()
        {
            Thread.Sleep(2000);
            var review = _context.Reviews.FindTheLatest(1).Single();
            return PartialView("_Review", review);
        }

        public ActionResult Index(string rating)
        {
            var list = new List<string>();
            list.Add("Aprovado");
            list.Add("Desaprovado");
            ViewBag.Ratings = list;

            if (rating == "Aprovado")
            {
                var model =
                    _context.Reviews
                        .OrderByDescending(r => r.Rating)
                        .Where(r => r.Rating >= 7);
                return View(model);
            }
            if (rating == "Desaprovado")
            {
                var model =
                    _context.Reviews
                        .OrderByDescending(r => r.Rating)
                        .Where(r => r.Rating < 7);
                return View(model);
            }
            var models =
               _context.Reviews
                   .OrderByDescending(r => r.Rating);

            return View(models);
        }

        //
        // GET: /Reviews/Details/5

        public ActionResult Details(int id)
        {
            var model = _context.Reviews.Single(r => r.Id == id);
            return View(model);
        }

        //
        // GET: /Reviews/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Reviews/Create

        [HttpPost]
        public ActionResult Create(Review review)
        {
            _context.Reviews.Add(review);
            _context.SaveChanges();
            return RedirectToAction("Index");
        }

        //
        // GET: /Reviews/Edit/5

        public ActionResult Edit(int id)
        {
            Review person = _context.Reviews.Find(id);
            return View(person);
        }

        //
        // POST: /Reviews/Edit/5

        [HttpPost]
        public ActionResult Edit(Review person)
        {
            if (ModelState.IsValid)
            {
                _context.Entry(person).State = EntityState.Modified;
                _context.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(person);
        }
    }
}
